<script setup lang="ts">
import { provide, ref } from 'vue'
import { onLaunch } from '@dcloudio/uni-app'
import { debugWarn } from '@tuniao/tnui-vue3-uniapp/utils'
import {
  getGradesApi,
  getAllGrades,
  getSettingAPi,
  getMyBookListAPi,
} from '@/services/api'
import storageApi from '@/utils/storage'
import { useUserStore } from '@/stores'
import { BASE_URL } from '@/config'
const userStore = useUserStore()

const code = ref('')
const globalData = {
  privacyContractName: '', //隐私协议的名字
  showPrivacy: false, //控制隐私弹窗显隐
}
provide('globalData', globalData)

onLaunch(async () => {
  const envVersion = __wxConfig.envVersion
  console.log(`当前环境是:${envVersion}, 域名为: ${BASE_URL}`)

  wx.setInnerAudioOption({ obeyMuteSwitch: false })
  //隐私授权
  getPrivacy()
  // 加载字体
  uni.loadFontFace({
    family: 'tuniao-xiaowei',
    source:
      'url("https://resource.tuniaokj.com/images/vue3-template/template2-website/font/tuniao-xiaowei.ttf")',
    fail: (err) => {
      debugWarn('load-font', `加载字体失败: ${err}`)
      console.error(err)
    },
  })

  //登录
  await handleLogin()
  //检测设备连接状态
  //获取系统设置
  await getSetting()
  //全局设置使用的教材
  await getBindBookId()
  userStore.setIfOnLunch(true)
})
//全局设置使用的教材
const getBindBookId = async () => {
  const data = await getMyBookListAPi()
  if (data.code === 200) {
    data.data.bindBookList.forEach((item) => {
      if (item.useStatus == 1) {
        userStore.setBookId(item.bookId)
        userStore.setMyUseBook(item)
        // uni.switchTab({
        //   url: '/pages/index/index',
        // })
        // userStore.setBookId('')
      }
    })
    // if (data.data.bindBookList.length) {
    //   uni.switchTab({
    //     url: '/pages/index/index',
    //   })
    // } else {
    //   uni.navigateTo({
    //     url: '/pages/bindBook/index',
    //   })
    // }
  }
}
//获取系统设置
const getSetting = async () => {
  const data = await getSettingAPi()
  if (data.code === 200) {
    const object = data.data
    userStore.setListenChinese(object.listenChineseStatus)
    userStore.setReadChinese(object.readChineseStatus)
    userStore.setOrder(object.playOrder)
    userStore.setSoundSpeed(object.playSpeed)
    userStore.setSoundPeople(object.pronunciationType)
  }
}

const handleLogin = async () => {
  await wrapWxLoginAsPromise()
  await getAccessToken()
}

const getAccessToken = async () => {
  let params = {
    tag: 'wechat_miniprogram',
    client_id: '2d737aa91d759a1c52d0',
    code: code.value,
  }
  try {
    const response = await uni.request({
      url: 'https://auth.xming-ai.com/api/login/oauth/access_token',
      method: 'POST',
      data: params,
      header: {
        'Content-Type': 'application/x-www-form-urlencoded',
      },
    })

    const { access_token, token_type } = response.data
    storageApi.set('token', `${token_type} ${access_token}`)

    // 在这里可以继续使用await来调用其他异步方法
    // await userStore.checkUserSn();
    await userStore.getUserInfo()

    // 返回成功信息或数据
    return response.data
  } catch (error) {
    // 处理请求错误
    console.error('Login request failed:', error)
    throw error
  }
  // uni.request({
  //   url: 'https://auth.xming-ai.com/api/login/oauth/access_token',
  //   method: 'POST',
  //   data: params,
  //   header: {
  //     'Content-Type': 'application/x-www-form-urlencoded',
  //   },
  //   success: (res) => {
  //     const { access_token, token_type } = res.data
  //     storageApi.set('token', `${token_type} ${access_token}`)
  //     // 获取是否绑定设备
  //     // userStore.checkUserSn()
  //     userStore.getUserInfo()
  //   },
  // })
}

const wrapWxLoginAsPromise = () => {
  return new Promise((resolve, reject) => {
    uni.login({
      provider: 'weixin',
      success: (res) => {
        code.value = res.code
        resolve(res)
      },
      fail: (err) => {
        reject(err)
      },
    })
  })
}
//隐私授权
const getPrivacy = () => {
  return new Promise((resolve, reject) => {
    wx.getPrivacySetting({
      success(res) {
        console.log(
          '是否需要授权：',
          res.needAuthorization,
          '隐私协议的名称为：',
          res.privacyContractName
        )
        if (res.needAuthorization) {
          globalData.privacyContractName = res.privacyContractName
          globalData.showPrivacy = true
        } else {
          globalData.showPrivacy = false
        }
      },
    })
  })
}
</script>
<style lang="scss">
@import '@tuniao/tn-style/dist/uniapp/index.css';
@import '@/static/css/custom.scss';
page {
  background-color: #f1f5fb;
  // padding-bottom: 20rpx;
}
</style>
